import React, { PureComponent, createRef } from 'react';
import { withRouter } from 'react-router-dom';

import { selectedAddressAction } from '@store/actionCreators'
import { store } from '@store'
import { createPurchaseOrder, updateOption, updateOrderAddress } from '@api/home';

import { Modal, Toast } from 'antd-mobile';
import { PopupStyle } from './style';
import { GoodsItem, ForwardCartTypeOption, ForwardGoodsOption, ForwardCounter } from './component'
import { updateOrder } from '../../../../../store/actionCreators';



class MinGoodsDetail extends PureComponent {

  state = {
    minDetail: {},
    goodsNum: 1,
    goodsOption: '',
    addressId: '',
    packTypeIndex: -1,
  }

  cartOption_ref = createRef()
  goodsOption_ref = createRef()
  counter_ref = createRef()

  pop_ref = createRef()

  uniacid = store.getState().appConfig.uniacid
  isApplet = store.getState().appConfig.isApplet


  async componentDidMount() {

    localStorage.removeItem('fullLoad') // 确保进去submit 前 不存在旧的 缓存

    let params = {
      id: this.props.id,
      uniacid: this.uniacid,
    }
    let res = await createPurchaseOrder(params)
    this.setState({
      minDetail: res.data,
      gid: this.props.id
    })
  }



  componentWillUnmount() {

    // this.cartOption_ref.current.removeEventListener('click', this.getTest(), false)
    // this.goodsOption_ref.current.removeEventListener('click', this.getTest(), false)
  }


  getCartNum = () => {
    // 获取装载量
    let _A_ = this.goodsOption_ref.current
    let _B_ = this.cartOption_ref.current

    const { cartSize, cartType } = _B_ ? JSON.parse(_B_.value) : ""
    const { guige, packaging_attributes } = this.state.minDetail

    console.log(guige?.length, guige?.[0]?.name, '+++', cartSize, cartType, '============')


    if (guige && guige.length > 0 && guige[0].name === '包装类型') {
      // 启用规格且设置 包装类型 规格
      const packIndex = _A_ ? JSON.parse(_A_.value).so_list[0] : null

      console.log('packIndex', packIndex)

      const packType = packaging_attributes[packIndex]

      console.log(packType, cartType, cartSize, '===========')

      if (cartSize && cartType && packType) {
        createPurchaseOrder({ packType, cartSize, cartType, uniacid: this.uniacid, id: this.props.id }).then(res => {
          console.log(res)
          this.setState({
            cartNum: parseInt(res.data.carnum)
          })

        })
      }

    } else {
      //  未启用规格
      console.log('未启用规格', cartSize, cartType)

      if (cartSize && cartType) {
        createPurchaseOrder({ packType: '', cartSize, cartType, uniacid: this.uniacid, id: this.props.id }).then(res => {
          console.log(res)
          this.setState({
            cartNum: parseInt(res.data.carnum)
          })

        })
      }
    }
  }


  render() {
    const { minDetail } = this.state

    console.log('弹窗渲染')

    return (
      <>

        <Modal
          visible={this.props.modal}
          maskClosable={true}
          transparent
          popup={true}
          onClose={e => { this.props.popupOnOff() }}
          animationType='slide-up'
          style={{
            backgroundColor: 'white',
            borderRadius: '.5rem .5rem 0 0'
          }}
        >
          <PopupStyle>
            {minDetail.good &&
              <div className="goods-option-popup" ref={this.pop_ref}>

                {/* 关闭按钮 */}
                <div className="close" onClick={e => { this.props.popupOnOff() }}>
                  <img src="https://res.lexiangpingou.cn/images/vip/chacha.png" alt="" />
                </div>

                <GoodsItem goods={minDetail.good} />

                {/* 车型规格 */}
                <ForwardCartTypeOption ref={this.cartOption_ref} gid={this.props.id} uniacid={this.uniacid} />
                {/* 商品规格 */}
                {minDetail.guige && <ForwardGoodsOption goodsOption={minDetail.guige} ref={this.goodsOption_ref} updateOptionPrice={(e) => { this.updateOptionNum(e) }} />}


                <div className="bottom" >
                  <ForwardCounter ref={this.counter_ref} />
                  <button className="caigou" onClick={e => { this.caigou() }}>
                    立即采购
                  </button>
                </div>



              </div>}
          </PopupStyle>
        </Modal>
      </>
    )
  }


  async updateOptionNum(specs) {
    // 更新规格商品信息

    let params = {
      id: this.props.id,
      specs,
      uniacid: this.uniacid
    }
    let res = await updateOption(params)
    if (res.status === 200) {
      this.setState({
        minDetail: res.data,
      })
    } else {
      console.log(res.msg)
    }
  }

  async caigou() {

    //  采购 预提交订单

    store.dispatch(updateOrder({
      orderno: null,
      acceptableTime: null,
      loadage: null,
      remark: "",
      isRead: false,
      agree: false
    }))

    const { guige, good, packaging_attributes } = this.state.minDetail
    const { defaultAddress } = store.getState()
    const { isApplet } = store.getState().appConfig

    let nowTime = new Date().getTime().toString().slice(0, -3)


    let [cartTypes, cartSize, packType, specs, specsList] = ["", "", "", "", ""]


    // 商品规格
    let _A_ = this.goodsOption_ref.current
    const goods_option = _A_ ? JSON.parse(_A_.value) : undefined

    if (goods_option) {
      // 排除商品无规格 
      specs = goods_option.specs
      specsList = goods_option.so_list
    } else {
      packType = ""
    }

    console.log(packType, packaging_attributes)

    // 规格中的包装类型
    // 无规格时 该数组 默认为 [""] 
    if (packaging_attributes[0] !== "") {

      //  guige[0].name === '包装类型'
      packType = packaging_attributes[specsList[0]]

      console.log(packaging_attributes[specsList[0]], '++++')

    }


    // 车辆属性参数
    let cartOptionParams = JSON.parse(this.cartOption_ref.current.value)
    cartSize = cartOptionParams.cartSize
    cartTypes = cartOptionParams.cartType

    // 需求数量
    let goodsNum = this.counter_ref.current.value


    let getCarNum = {
      uniacid: this.uniacid,
      id: this.props.id,
      cartType: cartTypes, // 车辆类型
      cartSize, // 车辆长度
      packType: packType, // 包装类型
    }

    let updateOrderAddressConfig = {
      deposit_orderno: '',
      province: defaultAddress.proc,
      city: defaultAddress.cityc,
      county: defaultAddress.countyc,
      detailed_address: defaultAddress.detailed_address
    }

    let createOrder = {
      uniacid: this.uniacid,
      id: this.props.id,  //商品id
      specs: specs, //商品规格
      addressid: defaultAddress.id,  // 地址id
      min_num: goodsNum, // 购买数量
      buy: '1', // 传 1 表示购买 
      cartType: cartTypes, // 车辆类型
      cartSize, // 车辆长度
      packType: packType, // 包装类型
      tuan_id: 0 // 团ID 0 不是团
    }

    if (!cartTypes || !cartSize) {
      Toast.info('请选择完整的车辆属性', 1)
      return
    }

    //  active_time
    if (parseInt(good.price_validity) < parseInt(nowTime)) {
      Toast.info('该商品供应价已过期')
    } else {

      createPurchaseOrder(getCarNum).then(res => {

        if (res.status === 200) {
          if (res.data.carnum) {

            console.log(res.data.carnum, '装载量')

            if (parseInt(goodsNum) > parseInt(res.data.carnum)) {
              Toast.info('购买数量超过承载量', 1)
            } else {

              if (parseInt(goodsNum) === parseInt(res.data.carnum)) {  // 购买数量等于 该组合规格装载量
                console.log('刚好满载')
                localStorage.setItem('fullLoad', 1)
              } else {
                localStorage.removeItem('fullLoad')
              }

              if (!guige || guige.length === 0) {
                // 商品无规格
                if (parseInt(goodsNum) > good.stock) {
                  Toast.info('购买数量超过现有库存', 1)
                } else {
                  createPurchaseOrder(createOrder).then(res => {

                    if (res.status === 200) {
                      let orderno = res.data
                      updateOrderAddressConfig.deposit_orderno = orderno
                      updateOrderAddress(updateOrderAddressConfig).then(res => {

                        store.dispatch(selectedAddressAction({})) // 清除 选择地址
                        //  res.status === 200 
                        this.props.popupOnOff()
                        isApplet ? window.navigateToWebWiew('/submit/' + orderno + '/' + 0) : this.props.history.push('/submit/' + orderno + '/' + 0)
                      })
                    } else {
                      Toast.fail(res.msg)
                    }
                  })
                }
              } else {
                if (specsList.length === guige.length) {
                  //   多规格，是否全选
                  if (parseInt(goodsNum) > good.stock) {
                    Toast.info('购买数量超过现有库存', 1)
                  } else {

                    createPurchaseOrder(createOrder).then(res => {
                      if (res.status === 200) {
                        let orderno = res.data
                        updateOrderAddressConfig.deposit_orderno = orderno
                        updateOrderAddress(updateOrderAddressConfig).then(res => {
                          // 修改订单地址
                          store.dispatch(selectedAddressAction({})) // 清除 选择地址
                          this.props.popupOnOff()
                          isApplet ? window.navigateToWebWiew('/submit/' + orderno + '/' + 0) : this.props.history.push('/submit/' + orderno + '/' + 0)
                        })
                      } else {
                        Toast.fail(res.msg)
                      }
                    })
                  }
                } else {
                  Toast.info('请先选择商品规格', 1)
                }
              }
            }
          } else {
            Toast.info('该组合未设置装载量', 1)
          }
        } else {
          Toast.info(res.msg, 1)
        }
      })
    }





  }


}



export default withRouter(MinGoodsDetail)